package com.le.tester.book.concurrentchallenge.synchronizedUtil14;

import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * createTime：2025-05-23 9:17
 * description：使用abstractQueueSynchronized实现的二元闭锁
 */
public class OneShotLatch {

    private final Sync sync = new Sync();

    public void signal() {
        sync.releaseShared(0);
    }

    public void await() throws InterruptedException {
        sync.acquireSharedInterruptibly(0);
    }

    private class Sync extends AbstractQueuedSynchronizer {

        protected int tryAcquireShared(int ignored) {
//            状态是1的话，表示success
            return (getState() == 1) ? 1 : -1;
        }

        public boolean tryReleaseShared(int ignored) {
            setState(1);
            return true;
        }

    }
}
